<?php
	$root = $_SERVER['DOCUMENT_ROOT'];
	include($root . "/util/session.php");//checks that the user is logged in
	include($root . "/util/privilege_check.php");
	checkPrivilege("student");

	if (isset($_POST['actualSubject']) or isset($_SESSION['actualSubject'])) {
		if(isset($_SESSION['actualSubject']) == false){
			$_SESSION['actualSubject'] = $_POST['actualSubject'];
		}
		$actualSubject = $_SESSION['actualSubject'];
		$query = "SELECT * FROM tests WHERE subjectID = '$actualSubject'";
		$result = mysqli_query($db,$query);
		#echo $_POST['actualSubject'];
		#$row = mysqli_fetch_assoc($result);
	}else{
		echo 'No subject exist. How did you get here?';
	}
	#$row=mysqli_fetch_assoc($result);
	#echo $row['subjectID'];
?>

<html>
	<head>
		<title>Possible exams: <?php echo $_SESSION['actualSubject']?></title>
		<link rel="stylesheet" type="text/css" href="studentStyle.css">
	</head>
	<body>
		<?php
			include($root . "/student/header.php")
		?>
		<li><a href="/student/checkExams.php">Back</a></li>
		<div id="menu">
			<ul>
				<b>Available chapters</b>
				<?php
						date_default_timezone_set('Europe/Madrid');
						$today = date("Y-m-d H:i:s");
						$username = $_SESSION['login_user'];
						$query2 = "SELECT chapterID FROM results WHERE subjectID = '$actualSubject' and studentUser = '$username'";
						$result2 = mysqli_query($db,$query2);
						$chaptersDone = array(); # dodging repeating that tedious exam again
						while($res = mysqli_fetch_assoc($result2)){
							$chaptersDone[] = $res['chapterID'];
						}

						#echo $today;
						while($row = mysqli_fetch_assoc($result)){
							$startDate = $row["startDate"];
							$endDate = $row["endDate"];
							if($today >= $startDate and $today < $endDate and (!in_array($row["chapterID"], $chaptersDone))){ #control if the exam is available or not
								echo 'for ' . $row["subjectID"];
								echo '<form action="/student/actualExam.php" method="POST">' .
					            '<input type="hidden" value="' . $row["subjectID"] . '" name="actualSubject">' .
					            '<input type="hidden" value="' . $row["numQuestions"] . '" name="questionNumber">' .
					            '<input type="submit" value="' . $row["chapterID"] . '" name="actualChapter"></form>';
				        	}
						}
				?>
			</ul>
		</div>
		<?php
			include($root . "/student/footer.php")
		?>
	</body>
</html>